package com.cat.binaryTree;

import java.util.*;

/**
*   @description https://leetcode.cn/problems/binary-tree-level-order-traversal-ii/?envType=problem-list-v2&envId=stfxhiIc
*   @author 曲大人的喵
*   @create 2025/9/20 16:36
*   @since JDK17
*/

public class Solution54 {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> ans = new ArrayList<>();
        if (root == null) {
            return ans;
        }
        Deque<TreeNode> q = new ArrayDeque<>();
        q.offer(root);
        while (!q.isEmpty()) {
            ArrayList<Integer> list = new ArrayList<>();
            for (int i = 0, j = q.size(); i < j; i++) {
                var x = q.poll();
                list.add(x.val);
                if (x.left != null) {
                    q.offer(x.left);
                }
                if (x.right != null) {
                    q.offer(x.right);
                }
            }
            ans.add(list);
        }
        Collections.reverse(ans);
        return ans;
    }
}
